<template>
<div>
  <img src="../../assets/images/account-security.jpeg" style="margin-left:30%;width: 25%;height: 25%">
  <Form ref="passwd" :model="passwordForm" :rules="ruleCustom" class="edit-form" style="margin-top: 20px">
    <FormItem class="userItem" prop="oldPassword">
      <label for="oldPassword">旧密码:</label>
      <Input id="oldPassword" v-model="passwordForm.oldPassword" class="userInput" type="password" placeholder="请输入您的旧密码"/>
    </FormItem>
    <FormItem class="userItem" prop="newPassword">
      <label for="newPassword" >新密码:</label>
      <Input id="newPassword" v-model="passwordForm.newPassword" class="userInput" type="password" placeholder="请输入您的新密码"/>
    </FormItem>
  </Form>
  <Button type="primary"
          @click="handleSave('passwd')"
          class="save">
    保存</Button>
</div>
</template>

<script>
    import {updatePassword} from "@/utils/api";

    export default {
        name: "",
      data(){
        const validatePass = (rule, value, callback) => {
          if (value === '') {
            callback(new Error('密码不能为空'));
          }
          callback();
        };
        return{
          passwordForm:{
            oldPassword: "",
            newPassword: ""
          },
          ruleCustom: {
            oldPassword: [
              { validator: validatePass, trigger: 'blur' }
            ],
            newPassword: [
              { validator: validatePass, trigger: 'blur' }
            ]
          }
        }
      },
    methods:{
      handleSave(name){
        this.$refs[name].validate((valid) => {
          if (valid) {
            //发送更新请求
            updatePassword(this.passwordForm).then((res)=>{
              if(res.code==200){
                this.$Message.success('修改成功，请重新登录!');
                sessionStorage.removeItem("token")//删除本地缓存的token
                this.$router.push("/login")
              }else{
                this.$Message.error('保存失败：'+res.codeInfo);
              }
            })
          } else {
            this.$Message.error('请按要求填写信息!');
          }
        })
      },
    },
    }
</script>

<style scoped>
  .userItem {
    margin-top: 3px;;
    margin-bottom: 40px;
  }
  label{
    width: 15%;
    display: inline-block;
    margin-left: 25px
  }
  .userInput{
    width: 40%;
    margin-left: 25px;
  }
  .save{
    width:15%;
    margin-left: 35%;
    margin-top: 80px;
    margin-bottom: 80px;
    border-radius: 5px
  }
</style>
